package top.go2do.common.utils;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @Description
 * @Author xingyj
 * @CreateTime 2025/5/21 06:40
 */

@Slf4j
public class VersionUtils {

    public static String generateVersion(Object entity, String operator) {
        // 1. 添加时间戳和操作者信息
        String metadata = String.format("%s-%d", operator, System.currentTimeMillis());

        // 2. 合并数据和元数据
        String fullData = JSONUtil.toJsonStr(entity) + "|" + metadata;

        // 3. 生成哈希（使用 SHA-256 更安全）
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hashBytes = digest.digest(fullData.getBytes(StandardCharsets.UTF_8));
            return Base64.getUrlEncoder().withoutPadding().encodeToString(hashBytes).substring(0, 12);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
